import os
from pprint import pprint

# 路径拼接 - 自动处理分隔符
full_path = os.path.join("父文件夹", "子文件夹", "文件.txt")
print(full_path)  # Linux/Mac: 父文件夹/子文件夹/文件.txt
# Windows: 父文件夹\子文件夹\文件.txt
import os

path = "/home/user/documents/file.txt"

# 获取文件名
print(os.path.basename(path))  # file.txt

# 获取目录名
print(os.path.dirname(path))  # /home/user/documents

# 分割路径
print(os.path.split(path))  # ('/home/user/documents', 'file.txt')
import os

# 分离文件名和扩展名
name, ext = os.path.splitext("example.tar.gz")
print(name)  # example.tar
print(ext)  # .gz
import os

# 获取绝对路径
print(os.path.abspath("file.txt"))  # 不解析符号链接
print(os.path.realpath("file.txt"))  # 解析符号链接
import os
from datetime import datetime

path = os.path.abspath("data.json")

# 检查路径属性
print(os.path.exists(path))  # True/False
print(os.path.isfile(path))  # True/False
print(os.path.isdir(path))  # True/False
print(os.path.islink(path))  # True/False

# 获取文件信息
if os.path.isfile(path):
    print(f"文件大小: {os.path.getsize(path)} 字节")
    print(
        f"获取最后修改时间: {datetime.fromtimestamp(os.path.getmtime(path)).strftime('%Y-%m-%d %H:%M:%S')}"
    )
    print(
        f"获取最后访问时间: {datetime.fromtimestamp(os.path.getatime(path)).strftime('%Y-%m-%d %H:%M:%S')}"
    )
    print(
        f"获取文件创建的时间: {datetime.fromtimestamp(os.path.getctime(path)).strftime('%Y-%m-%d %H:%M:%S')}"
    )
from pathlib import Path

# 创建路径对象
path1 = Path("data.json")  # 绝对路径
path2 = Path("./data.json")  # 相对路径
path3 = Path.cwd()  # 当前工作目录
path4 = Path.home()  # 用户主目录

print(f"绝对路径: {path1}")
print(f"相对路径: {path2}")
print(f"当前目录: {path3}")
print(f"用户主目录: {path4}")
from pathlib import Path

p = Path("D:/rs_ai_practice/python/practice/2025/10/data.json")

# 路径组成部分
print(f"完整路径: {p}")  # /home/user/example/file.txt
print(f"文件名: {p.name}")  # file.txt
print(f"文件名(无后缀): {p.stem}")  # file
print(f"扩展名: {p.suffix}")  # .txt
print(f"父路径: {p.parent}")  # /home/user/example
print(f"磁盘/锚: {p.anchor}")  # Linux: /, Windows: C:\
# 路径修改方法
print(f"替换文件名: {p.with_name('data.csv')}")  # /home/user/example/data.csv
print(f"替换扩展名: {p.with_suffix('.md')}")  # /home/user/example/file.md
# 基本检查
print(f"是否存在: {p.exists()}")
print(f"是否为文件: {p.is_file()}")
print(f"是否为目录: {p.is_dir()}")
print(f"是否为绝对路径: {p.is_absolute()}")
print(f"绝对路径: {p.resolve()}")
# 安全地获取文件信息
if p.is_file():
    stat = p.stat()
    print(f"文件大小: {stat.st_size} 字节")
    print(
        f"最后修改: {datetime.fromtimestamp(stat.st_mtime).strftime('%Y-%m-%d %H:%M:%S')}"
    )
else:
    print("不是文件，无法获取大小和时间")
from pathlib import Path

folder = Path("../10")

# 遍历目录内容（非递归）
for item in folder.iterdir():
    print(item)

# 使用通配符查找文件
for py_file in folder.glob("*.py"):
    print(py_file)

# 递归查找文件
for py_file in folder.rglob("*.py"):
    print(py_file)
import os
from pathlib import Path

# 获取当前工作目录
current_dir = os.getcwd()  # 返回字符串
print(f"当前工作目录: {current_dir}")

# 使用 pathlib 获取当前目录
current_path = Path.cwd()  # 返回 Path 对象
print(f"当前路径: {current_path}")

# 获取用户主目录
home_dir = Path.home()
print(f"用户主目录: {home_dir}")
from pathlib import Path
import os

# 根据操作系统选择路径
if os.name == "nt":  # Windows
    path = Path("C:/Users/Name/Documents")
else:  # Unix/Linux/Mac
    path = Path("/home/name/documents")

# 路径拼接
file_path = path / "subfolder" / "file.txt"
print(f"文件路径: {file_path}")

# 转换为字符串
path_str = str(file_path)
print(f"字符串路径: {path_str}")
from pathlib import Path


def find_files_by_extension(directory, extension):
    """查找指定目录下指定扩展名的所有文件"""
    directory_path = Path(directory)
    return list(directory_path.rglob(f"*{extension}"))


# 使用示例
python_files = find_files_by_extension(".", ".py")
print("找到的 Python 文件:")
for file in python_files:
    print(f"  {file}")


def get_file_info(file_path):
    """获取文件的详细信息"""
    path = Path(file_path)
    if path.exists() and path.is_file():
        stat = path.stat()
        return {
            "name": path.name,
            "size": stat.st_size,
            "modified": stat.st_mtime,
            "absolute_path": str(path.absolute()),
        }
    return None


# 使用示例
if python_files:
    file_info = get_file_info(python_files[0])
    pprint(f"文件信息:")
    pprint(file_info)

import shutil

def create_backup(file_path):
    """创建文件备份"""
    path = Path(file_path)
    if path.exists() and path.is_file():
        backup_path = path.with_suffix('.bak')
        shutil.copy2(path, backup_path)
        return backup_path
    return None

# 使用示例
backup_file = create_backup('example.txt')
if backup_file:
    print(f"备份文件: {backup_file}")